package data {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import utils.Utilities;
	/**
	 * ...
	 * @author Vjekoslav Ratkajec
	 */
	public class Floor extends EventDispatcher {
		
		private var apartmentList:Array;
		private var _floorNumber:int = -1;
		
		public function Floor(floorNumber:int) {
			_floorNumber = floorNumber;
			init();
		}
		
		private function init():void {
			apartmentList = new Array();
			loadFloorXML();
		}
		
		private function loadFloorXML():void {
			var url:String =  "http://www.ban-centar.hr/xml/searchbyfloor/" + floorNumber;
			try {
				Utilities.loadURL(url, loadFloorXML_Complete);
			} catch (e:Error) {
				//If error occurs, display it and set floor as empty, so no data will be fetched and shown
				trace(e);
				apartmentList = new Array();
				this.dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		private function loadFloorXML_Complete(event:Event):void {
			var xml:XML = XML(event.target.data);
			
			for each(var item:XML in xml.children()) {
				var id:int = item.id;
				var code:String = String(item.code);
				var state:String = String(item.state);
				var price:String = Utilities.getMoney(Number(item.price));
				var apt:ApartmentBasic = new ApartmentBasic(id, code, state, price);
				apartmentList.push(apt);
			}
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function getApartmentByName(name:String):ApartmentBasic {
			for each (var apt:ApartmentBasic in apartmentList) {
				if (apt.code == name) {
					return apt;
				}
			}
			return null;
		}
		
		public function get floorNumber():int {
			return _floorNumber;
		}
		
	}

}